<?php

namespace app\admin\controller;

use app\BaseController;
use app\admin\model\User as ModelUser;
use app\admin\validate\User;
use think\exception\ValidateException;
use think\facade\Session;

class Login extends BaseController
{
    public function Index()
    {
        $this->logs('[管理员]登录视图');
        if(!$this->admin)
        {
            return view();
        }else{
            return redirect('/admin/index');
        }
    }
    public function doLog()
    {
        $this->logs('[管理员]登录');

        if(request()->isPost())
        {
            $isLog = Session::has('admin');
            if ($isLog) return error('无需重复登录');
            $param = input();
            try {
                // 一个用户对应多个角色 文章管理 日志管理 --
                validate(User::class)->scene('login')->check($param);
                if (!captcha_check($param['captcha']))  return error('验证码错误');
                $userData = ModelUser::where('username' , $param['username'])->find();
                if (empty($userData) || !$userData->role)  return error('管理员不存在');
                $password =  md5(config('secure.secret_key') . $param['password']);
                if ($userData['password'] != $password) return error('账号或密码错误');
                if ($userData['status'] == '0') return error('该账户已被封禁');
                else {
                    $data = [
                        'nickname' => $userData['nickname'],
                        'user_id' => $userData['id'],
                        'headIcon' => $userData['head_icon'],
                    ];
                    Session::set('admin', $data);
                    ModelUser::where('id', $userData['id'])->update(['login_time' => time()]);
                    return success();
                }
                return error('登录失败');
            } catch (ValidateException  $e) {
                return error($e->getMessage());
            }
        }
    }
    public function logout()
    {
        $this->logs('[管理员]退出登录');
        if (Session::has('admin')) {
            Session::set('admin', null);
            Session::destroy();
            echo "<script>alert('退出成功');window.location.href='/admin/'</script>";
        }
    }
}
